<template>
  <div>
    <div style="margin-top: 1%;text-align:center;">
      <el-button @click="returnPage()" style="font-size: 20px;" type="primary">返回</el-button>
      <el-button @click="saveGradeTemps('handle')" type="primary"
                 style="font-size: 20px;margin-right: 1%">暂存</el-button>
      <el-select  v-model="form.clazzId"
                  style="width: 22%;margin-right: 1%"
                  clearable filterable
                  placeholder="请选择班级">
        <el-option v-for="item in clazz" :key="item.clazzId"
                   :label="item.clazzId + '班'" :value="item.clazzId">
        </el-option>
        <el-option label="其它学生" :value="''"/>
      </el-select>
      <el-button @click="findGradeTemps()" style="font-size: 20px;" type="info">立即查看</el-button>
      <el-button @click="exportExcel()" style="font-size: 20px;" type="primary">导出Excel</el-button>
      <el-button @click="importExcel()" style="font-size: 20px;" type="primary">导入Excel</el-button>
      <el-button @click="subScoreMGMT()" style="font-size: 22px;margin-left: 1%" type="warning">子成绩管理</el-button>
      <el-button @click="submitGrades()" style="font-size: 22px;margin-left: 2%" type="danger">提交成绩</el-button>
    </div>
    <div style="margin-top: 1%;text-align:center;">
      <span style="font-size:22px;">课程名称: </span>
      <span style="font-size:22px;font-weight: bold;color:blueviolet">{{course.courseName}}</span>
      <span style="font-size:22px;">; 平时成绩:</span>
      <span style="font-size:22px;font-weight: bold">{{teachTask.usualPct}}%</span>
      <span style="font-size:22px;">; 实践成绩:</span>
      <span style="font-size:22px;font-weight: bold">{{teachTask.expPct}}%</span>
      <span style="font-size:22px;">; 期中成绩:</span>
      <span style="font-size:22px;font-weight: bold">{{teachTask.midPct}}%</span>
      <span style="font-size:22px;">; 期末成绩:</span>
      <span style="font-size:22px;font-weight: bold">{{teachTask.finalPct}}%</span>
      <span style="font-size:22px;">; 其它成绩:</span>
      <span style="font-size:22px;font-weight: bold">{{teachTask.otherPct}}%; </span>
      <span style="font-size:22px;color: #e6a23c;">及格分:</span>
      <span style="font-size:22px;font-weight: bold;color: #e6a23c;">{{teachTask.passingScore}}; </span>
      <span style="font-size:22px;color: #67c23a;"> 满分:</span>
      <span style="font-size:22px;font-weight: bold;color: #67c23a">{{teachTask.fullScore}};</span>
    </div>
    <template style="margin-top: 2%">
      <el-table :data="pageInfo.list" style="width: 100%">
        <el-table-column label="" width="60">
        </el-table-column>
        <el-table-column label="学号" width="220" prop="stuId" sortable>
          <template slot-scope="scope">
            <span>{{scope.row.stuId}}</span>
          </template>
        </el-table-column>
        <el-table-column label="姓名" width="220">
          <template slot-scope="scope">
            <span>{{scope.row.stuName}}</span>
          </template>
        </el-table-column>
        <el-table-column label="平时成绩"  width="200">
          <template slot-scope="scope">
            <el-input v-model="scope.row.usualScore"
                      v-if="teachTask.usualPct > 0"
                      style="font-size:22px;font-weight: bold"
                      oninput ="value=value.replace(/[^0-9]/g,'')"
                      @keyup.native="updateTotalScore(scope.row)">
            </el-input>
          </template>
        </el-table-column>
        <el-table-column label="实践成绩"  width="200">
          <template slot-scope="scope">
            <el-input v-model="scope.row.expScore"
                      v-if="teachTask.expPct > 0"
                      style="font-size:22px;font-weight: bold"
                      oninput ="value=value.replace(/[^0-9]/g,'')"
                      @keyup.native="updateTotalScore(scope.row)">
            </el-input>
          </template>
        </el-table-column>
        <el-table-column label="期中成绩"  width="200">
          <template slot-scope="scope">
            <el-input v-model="scope.row.midScore"
                      v-if="teachTask.midPct > 0"
                      style="font-size:22px;font-weight: bold"
                      oninput ="value=value.replace(/[^0-9]/g,'')"
                      @keyup.native="updateTotalScore(scope.row)">
            </el-input>
          </template>
        </el-table-column>
        <el-table-column label="期末成绩"  width="200">
          <template slot-scope="scope">
            <el-input v-model="scope.row.finalScore"
                      v-if="teachTask.finalPct > 0"
                      style="font-size:22px;font-weight: bold"
                      oninput ="value=value.replace(/[^0-9]/g,'')"
                      @keyup.native="updateTotalScore(scope.row)">
            </el-input>
          </template>
        </el-table-column>
        <el-table-column label="其它成绩"  width="200">
          <template slot-scope="scope">
            <el-input v-model="scope.row.otherScore"
                      v-if="teachTask.otherPct > 0"
                      style="font-size:22px;font-weight: bold"
                      oninput ="value=value.replace(/[^0-9]/g,'')"
                      @keyup.native="updateTotalScore(scope.row)">
            </el-input>
          </template>
        </el-table-column>
        <el-table-column label="预估最终成绩"  width="160">
          <template slot-scope="scope">
                        <span v-if="parseInt(scope.row.totalScore) >= parseInt(teachTask.passingScore)"
                              style="color: #67C23A;font-size:24px;font-weight: bold">{{scope.row.totalScore}}</span>
            <span v-if="parseInt(scope.row.totalScore) < parseInt(teachTask.passingScore)"
                  style="color: #F56C6C;font-size:24px;font-weight: bold">{{scope.row.totalScore}}</span>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-bottom: 1%;"></div>
      <el-pagination
          style="text-align: center;"
          background
          layout="total,prev, pager, next"
          :total="pageInfo.total"
          :page-size="pageInfo.pageSize"
          @current-change="handleCurrentChange">
      </el-pagination>
    </template>
    <el-dialog title="上传文件" :visible.sync="dialogForm" :before-close="handleClose">
      <div style="margin:0 auto;text-align:center;width: 60%">
        <el-upload
            class="upload-demo"
            action=""
            :on-change="handleChange"
            :on-exceed="handleExceed"
            :on-remove="handleRemove"
            :file-list="fileListUpload"
            :limit="1"
            accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
            :auto-upload="false">
          <el-button size="small" style="width: 192px;height: 108px;font-size: 32px" type="primary">点击导入</el-button>
        </el-upload>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data(){
    return {
      dialogForm: false,
      form:{
        teachId: '',
        clazzId: '',
        courseId: '',
      },
      teachTask:{},
      course:{},
      clazz:[],
      currPage: 1,
      pageInfo:{},
      modify: false,
      modifyList:[],//在页面中已修改的数据
      fileListUpload: [],//已上传的文件集合
      fileTemp: null,// 关键！！！！存放组件上传的excel file 用于实现读取数据
    }
  },
  created() {
    this.form.teachId = this.$route.params.teachId;
    this.taskInit();//课程安排初始化
  },
  methods:{
    submitGrades(){//提交成绩
      this.saveGradeTemps();
      this.$confirm('您真的要提交成绩吗?').then(()=>{//提交成绩提示
        let path = 'http://localhost:8081/grade/submitGrades/try';
        this.$ajax.post(path,this.teachTask).then(res=>{
          if(res.data.status === 0){
            this.$confirm(res.data.message).then(()=>{//再次确认提交
              path = 'http://localhost:8081/grade/submitGrades/confirm';
              this.$ajax.post(path,this.teachTask).then(res=>{
                if(res.data.status === 0){//提交成功
                  this.$message.success(res.data.message);
                  this.returnPage();//退出页面
                }
              })
            })
          }
          else{//提交异常
            this.$message.error(res.data.message);
            if(res.data.status === 2)//教学安排不存在或状态不为进行中
              this.returnPage();//退出当前页面
          }
        })
      })
    },
    subScoreMGMT(){//子成绩管理
      this.$router.push(`/teacher/subProjectMGMT/${this.form.teachId}`);
    },
    importExcel(){//excel导入
      this.dialogForm = true;
    },
    uploadExcelData(list){//将文件内容传输到后台保存
      let data = list.map(item => {
        return {
          teachId: this.teachTask.teachId,
          stuId: item.学号,
          usualScore: item.平时成绩,
          expScore: item.实践成绩,
          midScore: item.期中成绩,
          finalScore: item.期末成绩,
          otherScore: item.其它成绩,
        }
      })
      let task = this.teachTask;
      data.forEach(function (item) {
        if(task.usualPct === 0 || isNaN(item.usualScore) || item.usualScore > task.fullScore
            || item.usualScore < 0){//占总分比例为0 非数字 大于满分 复数则置空
          item.usualScore = '';
        }
        if(task.expPct === 0 || isNaN(item.expScore) || item.expScore > task.fullScore
            || item.expScore < 0){
          item.expScore = '';
        }
        if(task.midPct === 0 || isNaN(item.midScore) || item.midScore > task.fullScore
            || item.midScore < 0){
          item.midScore = '';
        }
        if(task.finalPct === 0 || isNaN(item.finalScore) || item.finalScore > task.fullScore
            || item.finalScore < 0){
          item.finalScore = '';
        }
        if(task.otherPct === 0 || isNaN(item.otherScore) || item.otherScore > task.fullScore
            || item.otherScore < 0){
          item.otherScore = '';
        }
      })
      let path = 'http://localhost:8081/grade/uploadGradeTempsExcel';
      this.$ajax.post(path,data).then(res=>{
        if(res.data.status === 0){
          this.$message.success('已成功为您保存了excel表格中的数据!');
        }
      })
    },
    exportExcel(){//excel导出
      this.saveGradeTemps();
      let path = 'http://localhost:8081/grade/getGradeTempsExcel';
      this.$ajax.post(path,this.form).then(res=>{
        let fileName =this.teachTask.teacherId + ' - ' + this.course.courseName + ' - '
            + this.teachTask.teachName + ' - ' + (this.form.clazzId!==''?this.form.clazzId+'班':'其它学生');
        if(res.data.list != null && res.data.list.length > 0)
          this.export2Excel(res.data.list,fileName);
        else
          this.$message.error('没有可以导出的成绩清单!');
      })
    },
    findGradeTemps(){//查找
      this.currPage = 1;
      this.getData();
    },
    handleCurrentChange(val){//翻页
      this.currPage = val;
      this.getData();
    },
    getData(){//获取数据
      this.saveGradeTemps();
      let path = `http://localhost:8081/grade/getGradeTemps/${this.currPage}`;
      this.$ajax.post(path,this.form).then(res=>{
        this.pageInfo = res.data;
        for(let i = 0,list = this.pageInfo.list;list !== null && i < list.length;i++){
          this.updateTotalScore(list[i]);
        }
        this.modify = false;
        this.modifyList = [];//清空已记录的被改动列表
      })
    },
    saveGradeTemps(val){//暂存
      if(this.modify){
        let path = 'http://localhost:8081/grade/saveGradeTemps';
        this.$ajax.post(path,this.modifyList).then(res=>{
          if(res.data.status === 0){
            if(val === 'handle')
              this.$message.success('已成功为您暂存了数据!');
            else
              this.$message.success('已自动为您暂存了数据!');
            this.modify = false;
            this.modifyList = [];//清空已记录的被改动列表
          }
        })
      }
      else{
        if(val === 'handle')
          this.$message.warning('没有改动数据，无需保存!');
      }
    },
    updateTotalScore(row){//根据输入生成预估总分
      this.modify = true;
      let add = true;
      for(let i = 0,list = this.modifyList;i < list.length;i++){//已被记录则无需再次记录
        if(list[i].gradeTempId === row.gradeTempId){
          add = false;
          break;
        }
      }
      if(add){//记录下所有改动过的成绩缓存
        this.modifyList.push(row);
      }
      if(!(parseInt(row.usualScore) >= 0 && parseInt(row.usualScore) <= this.teachTask.fullScore))
        row.usualScore = '';
      if(!(parseInt(row.expScore) >= 0 && parseInt(row.expScore) <= this.teachTask.fullScore))
        row.expScore = '';
      if(!(parseInt(row.midScore) >= 0 && parseInt(row.midScore) <= this.teachTask.fullScore))
        row.midScore = '';
      if(!(parseInt(row.finalScore) >= 0 && parseInt(row.finalScore) <= this.teachTask.fullScore))
        row.finalScore = '';
      if(!(parseInt(row.otherScore) >= 0 && parseInt(row.otherScore) <= this.teachTask.fullScore))
        row.otherScore = '';
      let sum = row.usualScore * this.teachTask.usualPct + row.expScore * this.teachTask.expPct
          + row.midScore * this.teachTask.midPct + row.finalScore * this.teachTask.finalPct
          + row.otherScore * this.teachTask.otherPct;
      row.totalScore = Math.ceil(sum / 100);
    },
    taskInit(){//课程安排初始化
      let path = 'http://localhost:8081/teach/getTeachTasks/1';
      this.$ajax.post(path,this.form).then(res=>{
        let result = res.data.list[0];
        if(res.data.list.length === 1 && parseInt(result.teachState) === 1){
          this.teachTask = result;
          this.clazz = result.clazzes;
          this.getData();
          this.getCourse();
        }
        else{
          alert("课程安排不存在或没有权限!");
          this.returnPage();
        }
      })
    },
    getCourse(){//获得课程
      this.form.courseId = this.teachTask.courseId;
      let path = 'http://localhost:8081/course/getCourseList/1';
      this.$ajax.post(path,this.form).then(res=>{
        this.course = res.data.list[0];
      })
    },
    returnPage(){//返回
      this.$router.push('/teacher/teachTaskMGMT');
    },
    handleClose(done){//关闭操作
      this.$confirm('确认关闭?').then(()=>{
        done();
        this.fileListUpload = [];//清空上传文件集合
        this.getData();
      })
    },
    export2Excel(dataList,fileName) {//导出excel
      require.ensure([], () => {
        const { export_json_to_excel } = require('../../excel/Export2Excel');
        const tHeader = ['学号', '姓名','平时成绩','实践成绩','期中成绩','期末成绩','其它成绩'];
        const filterVal = ['stuId', 'stuName','usualScore','expScore','midScore','finalScore','otherScore'];
        const list = dataList;
        const data = list.map(v => filterVal.map(j => v[j]))//formatJson
        export_json_to_excel(tHeader, data, fileName);
      })
    },
    handleChange(file) {//导入excel所需方法
      this.fileTemp = file.raw;// file.raw 及上传的excel
    },
    handleExceed() {//导入excel所需方法
      this.$message.warning('一次只能上传一个文件!请先关闭其它文件再上传!');
    },
    handleRemove() {//导入excel所需方法
      this.fileTemp = null;
    },
    importExcelData(obj) {//导入excel所需方法
      let _this = this;
      // 通过DOM取文件数据
      this.file = obj;
      let rABS = false; //是否将文件读取为二进制字符串
      let f = this.file;
      let reader = new FileReader();
      FileReader.prototype.readAsBinaryString = function(f) {
        let binary = '';
        let rABS = false; //是否将文件读取为二进制字符串
        let wb; //读取完成的数据
        let outdata;
        let reader = new FileReader();
        reader.onload = function() {
          let bytes = new Uint8Array(reader.result);
          let length = bytes.byteLength;
          for (let i = 0; i < length; i++) {
            binary += String.fromCharCode(bytes[i]);
          }
          let XLSX = require('xlsx');
          if (rABS) {
            wb = XLSX.read(binary, {
              type: 'base64'
            });
          } else {
            wb = XLSX.read(binary, {
              type: 'binary'
            });
          }
          outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]); //outdata就是你想要的东西
          _this.uploadExcelData(outdata);
        };
        reader.readAsArrayBuffer(f);
      };
      if (rABS) {
        reader.readAsArrayBuffer(f);
      } else {
        reader.readAsBinaryString(f);
      }
    },
  },
  watch:{
    fileTemp(val) {//导入excel所需方法
      //console.log(val);//输出读取到的文件
      if (val) {
        if (val.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
            val.type === 'application/vnd.ms-excel'){//文件格式校验,只能上传xlsx/xls文件
          this.importExcelData(val);
        } else {
          this.$message.warning('附件格式错误，请删除后重新上传！');
        }
      }
    },
  },
  destroyed() {//手动跳转到其它页面时尝试保存页面数据
    this.saveGradeTemps();
  }
}
</script>

<style scoped>
span{
  font-size: 18px;
}
</style>